package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.constant.RedisConst;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    JedisPool jedisPool;

    @Reference
    MemberService service;

    @RequestMapping("/check")
    public Result check(@RequestBody Map<String,String> map){

        //获取手机号
        String telephone = map.get("telephone");
        //获取redis中的验证码
        String validateCodeR = jedisPool.getResource().get(RedisConst.SENDTYPE_LOGIN+"-"+telephone);
        //获取用户输入的验证码
        String validateCode = map.get("validateCode");
        if (!(validateCodeR!=null&&validateCodeR.equals(validateCode))){
            return new Result(false, MessageConst.VALIDATECODE_ERROR);

        }
       Member member =  service.findByTelephone(telephone);
        if (member == null){
            member = new Member();
            member.setRegTime(new Date());
            member.setPhoneNumber(telephone);
            service.add(member);
        }
        return new Result(true,MessageConst.LOGIN_SUCCESS);
    }
}
